//cms活动页
// pages/cmsActivity/cmsActivity.js
let url_js = require("../../utils/url.js");
let user_js = require("../../utils/user.js");
let common_js = require("../../utils/common.js");
let page_js = require("../../utils/pageOptions.js");
let sys_js = require("../../utils/system.js");
let cart_js = require("../../utils/cart.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '', //用来请求cms活动
    sysInfo: null,
    userInfo: null,
    cmsInfo: null,
    contentStatus: -1,
    pageScrollTop: 0,
    containerTouchmove: '',
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据
    containerPaddingBottom: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //0.禁止转发
    wx.hideShareMenu();
    //1.初始化数据
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //如果是分享进来的，并且没有选择角色，进入角色选择页面
    if (page_js.pageOptionsInfo()) {
      //2.relauch
      wx.reLaunch({
        url: '../indexSearchShop/indexSearchShop'
      });
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化options数据
  initUnShareOptionsData: function (options) {
    //userInfo
    let tempUserInfo = user_js.userInfo();
    //productId
    let tmpId = options.id ? options.id : '';
    if (!tmpId) {
      common_js.showToast("活动不存在！");
      return
    }

    //set data
    this.setData({
      id: tmpId,
      sysInfo: sys_js.systemInfo(),
      userInfo: tempUserInfo
    });
  },

  //初始化数据
  initData: function (options) {
    let tmpId = options.id ? options.id : '';
    //没有角色--->角色选择
    if (!user_js.hasRole()) {
      //1.save param
      let obj = {
        url: '../cmsActivity/cmsActivity',
        param: '?id=' + tmpId
      }
      page_js.savePageOptionsInfo(obj);
      //2.relauch
      //*********跳转放在onshow
      return;
    } else {
      //有角色，展示页面
      this.initUnShareOptionsData(options);
      //请求数据
      this.requestToGetCmsList(this.data.id);
    }
  },

  //获取cms详情
  requestToGetCmsList: function (cmsId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      id: cmsId,
      shopId: this.data.userInfo.ztd.id
    };
    api.wxRequest(url_js.cmsListUrl, data).then(res => {
      this.handleCmslistData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的商品列表数据
  handleCmslistData: function (res) {
    if (!res.result) {
      common_js.showToast("活动不存在！");
      return
    }
    let tmpInfo = res.result;
    //topPading 
    let tmpPaddintBottom = 0;
    if (tmpInfo.components && tmpInfo.components.length > 0) {
      let lastComponent = tmpInfo.components[tmpInfo.components.length - 1];
      //商品
      if (lastComponent.componentType == 3) {
        tmpPaddintBottom = 20;
      }
    }

    //1.set data
    this.setData({
      cmsInfo: tmpInfo,
      containerPaddingBottom: tmpPaddintBottom,
      contentStatus: 1
    });
    //2.设置标题
    wx.setNavigationBarTitle({
      title: tmpInfo.pageTitle
    });
    //3.开启转发
    wx.showShareMenu({});
  },

  //新用户领券
  requestToCouponPick: function (couponId, cIndex, index) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      couponId: couponId,
      shopId: this.data.userInfo.ztd.id,
    };
    api.wxRequest(url_js.couponPickCouponUrl, data).then(res => {
      this.handleCouponPickData(res, cIndex, index);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleCouponPickData: function (res, cIndex, index) {
    common_js.showToast("领取成功");

    let tmpObj = res.result;
    if (!tmpObj) return;

    let tmpCmsInfo = this.data.cmsInfo;
    let componentItem = tmpCmsInfo.components[cIndex];
    let item = componentItem.couponVos[index];
    item.pickStatus = tmpObj;
    this.setData({
      cmsInfo: tmpCmsInfo
    });
  },

  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  // 点击配置的图片
  onImagesItem: function (e) {
    let componentIndex = e.currentTarget.dataset.cindex;
    let index = e.currentTarget.dataset.index;
    let componentItem = this.data.cmsInfo.components[componentIndex];
    let item = componentItem.images[index];

    //跳转
    if (item.paramType == 0) return;
    //商品详情
    if (item.paramType == 2) {
      wx.navigateTo({
        url: '../goodsDetails/goodsDetails?productId=' + item.productId
      });
      return;
    }
    //其他
    if (item.paramType == 1) {
      //去掉头部的pages/
      let tmpLink = '../' + item.url;
      wx.navigateTo({
        url: tmpLink
      });
    }
  },

  //领取优惠券
  onGetCoupon: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    let componentIndex = e.currentTarget.dataset.cindex;
    let index = e.currentTarget.dataset.index;
    let componentItem = this.data.cmsInfo.components[componentIndex];
    let item = componentItem.couponVos[index];
    this.requestToCouponPick(item.id, componentIndex, index);
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cmsActivityLq);
  },

  //使用优惠券
  onUseCoupon: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    let componentIndex = e.currentTarget.dataset.cindex;
    let index = e.currentTarget.dataset.index;
    let componentItem = this.data.cmsInfo.components[componentIndex];
    let item = componentItem.couponVos[index];
    //

    wx.navigateTo({
      url: '../cmsGoodsList/cmsGoodsList?coupon=' + common_js.jsonStringify(item)
    })

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cmsActivityConponUse);
  },


  //查看登录状态，未登录直接跳转登录
  checkIsToLoginIndex: function () {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return false;
    }
    return true;
  },

  //添加商品
  onAddGoods: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    let componentIndex = e.currentTarget.dataset.cindex;
    let index = e.currentTarget.dataset.index;
    let componentItem = this.data.cmsInfo.components[componentIndex];
    let item = componentItem.productVos[index];

    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cmsActivityAdd);
  },

  //商品详情
  onGoodsDetail: function (e) {
    let componentIndex = e.currentTarget.dataset.cindex;
    let index = e.currentTarget.dataset.index;
    let componentItem = this.data.cmsInfo.components[componentIndex];
    let item = componentItem.productVos[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.cmsActivityShare);
    return this.shareAppMessage();
  },

  //获取分享的AppMessage
  shareAppMessage: function () {
    return {
      title: this.data.cmsInfo.pageTitle ? this.data.cmsInfo.pageTitle : '好想你心选',
      path: '/pages/cmsActivity/cmsActivity' + '?id=' + this.data.id,
      imageUrl: this.data.cmsInfo.mainImage
    }
  }
})